var express = require("express");
var jwt = require("jsonwebtoken"); // 引入jsonwebtoken
var router = express.Router();
var multer = require("multer");
var path = require("path");
var fs = require("fs");
const md5 = require("blueimp-md5");
// 引入短信依赖包
// const SMSClient = require("@alicloud/sms-sdk");

// 配置阿里云访问凭证
const accessKeyId = "LTAI5tGqaasq9JgSTPkM7mgj"; // 替换为您的 AccessKey ID
const secretAccessKey = "y80DZsuHIcmglWzSBejPNpGo2PpN7s"; // 替换为您的 AccessKey Secret

// 创建短信客户端
// const smsClient = new SMSClient({
//   accessKeyId,
//   secretAccessKey,
// });

// 引入数据库
var { UserModel } = require("../db/index");

// 定义密钥
const ACCESS_TOKEN_SECRET = "your_access_token_secret";
const REFRESH_TOKEN_SECRET = "your_refresh_token_secret";

// 存储验证码的对象，键为手机号，值为{code: 验证码, timestamp: 发送时间}
const verificationCodes = new Map();

// 发送短信验证码的接口
router.get("/send-sms", async (req, res) => {
  const { phoneNumber } = req.query;

  // 验证手机号格式
  if (!phoneNumber || !/^1[3-9]\d{9}$/.test(phoneNumber)) {
    return res.json({
      success: false,
      message: "请输入正确的手机号",
    });
  }

  try {
    // 生成随机验证码
    const code = Math.floor(100000 + Math.random() * 900000).toString();

    // 存储验证码和发送时间
    verificationCodes.set(phoneNumber, {
      code,
      timestamp: Date.now(),
    });

    // 开发环境直接返回验证码
    console.log("开发环境 - 手机号:", phoneNumber, "验证码:", code);

    res.json({
      success: true,
      message: "验证码发送成功",
      code: code, // 开发环境直接返回验证码
      dev_msg: "注意：这是开发环境模式，实际验证码会通过短信发送",
    });
  } catch (error) {
    console.error("服务异常:", error);
    res.json({
      success: false,
      message: error.message || "验证码发送失败，请稍后重试",
      error: error.code || "UNKNOWN_ERROR",
    });
  }
});

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, "../public/uploads/avatars");
    // 确保目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  },
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 只接受图片文件
  if (file.mimetype.startsWith("image/")) {
    cb(null, true);
  } else {
    cb(new Error("只能上传图片文件！"), false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024, // 限制5MB
  },
});

// 用户注册
router.post("/register", upload.single("avatar"), async function (req, res) {
  const { username, password, gender, age, phone, code } = req.body;

  // 参数验证（不包含头像）
  if (!username || !password || !gender || !age || !phone || !code) {
    // 如果上传了头像，删除它
    if (req.file) {
      fs.unlinkSync(req.file.path);
    }
    return res.send({
      code: 400,
      msg: "请填写所有必填信息",
    });
  }

  // 验证性别
  if (gender !== "男" && gender !== "女") {
    // 如果上传了头像，删除它
    if (req.file) {
      fs.unlinkSync(req.file.path);
    }
    return res.send({
      code: 400,
      msg: "性别只能是男或女",
    });
  }

  try {
    // 检查用户名是否已存在
    const existingUser = await UserModel.findOne({ userName: username });
    if (existingUser) {
      // 如果上传了头像，删除它
      if (req.file) {
        fs.unlinkSync(req.file.path);
      }
      return res.send({
        code: 400,
        msg: "用户名已存在",
      });
    }

    // 检查手机号是否已被注册
    const existingPhone = await UserModel.findOne({ phone: phone });
    if (existingPhone) {
      // 如果上传了头像，删除它
      if (req.file) {
        fs.unlinkSync(req.file.path);
      }
      return res.send({
        code: 400,
        msg: "手机号已被注册",
      });
    }

    // 获取头像URL（如果有上传的话）
    let avatarUrl = "";
    if (req.file) {
      avatarUrl = `/uploads/avatars/${req.file.filename}`;
    }

    // 创建新用户
    const newUser = new UserModel({
      userName: username,
      passWord: password,
      img: avatarUrl, // 如果没有上传头像，则为空字符串
      sex: gender,
      age: parseInt(age),
      phone: phone,
      money: 0,
      concern: [],
      vip: 0,
    });

    await newUser.save();

    res.send({
      code: 200,
      msg: "注册成功",
    });
  } catch (error) {
    // 如果出错且上传了头像，删除它
    if (req.file) {
      fs.unlinkSync(req.file.path);
    }
    console.error("注册错误:", error);
    res.send({
      code: 500,
      msg: "注册失败，请稍后重试",
    });
  }
});

// 用户登录
router.post("/login", async function (req, res, next) {
  let user = req.body;

  // 参数验证
  if (!user.username) {
    return res.send({
      code: 400,
      msg: "用户名不能为空",
    });
  }
  if (!user.password) {
    return res.send({
      code: 400,
      msg: "密码不能为空",
    });
  }
  if (user.username.length < 3 || user.username.length > 20) {
    return res.send({
      code: 400,
      msg: "用户名长度应在3-20个字符之间",
    });
  }
  if (user.password.length < 32) {
    return res.send({
      code: 400,
      msg: "密码格式不正确",
    });
  }

  // 查询用户
  let userInfo = await UserModel.findOne({
    userName: user.username,
  });

  if (!userInfo) {
    return res.send({
      code: 404,
      msg: "用户不存在",
    });
  }

  // 验证密码
  if (userInfo.passWord !== user.password) {
    return res.send({
      code: 401,
      msg: "密码错误",
    });
  }

  // 生成访问 Token
  const accessToken = jwt.sign({ id: userInfo._id }, ACCESS_TOKEN_SECRET, {
    expiresIn: "15m",
  });

  // 生成刷新 Token
  const refreshToken = jwt.sign({ id: userInfo._id }, REFRESH_TOKEN_SECRET, {
    expiresIn: "7d",
  });

  res.send({
    code: 200,
    msg: "登录成功",
    data: {
      userId: userInfo._id,
      username: userInfo.userName,
      avatar: userInfo.img,
      sex: userInfo.sex,
      age: userInfo.age,
      phone: userInfo.phone,
      money: userInfo.money,
      vip: userInfo.vip,
    },
    accessToken,
    refreshToken,
  });
});

// 刷新 Token
router.post("/refresh-token", async function (req, res, next) {
  const { refreshToken } = req.body;

  if (!refreshToken) {
    return res.send({
      code: 403,
      msg: "刷新 Token 不能为空",
    });
  }

  try {
    // 验证refresh token
    const decoded = jwt.verify(refreshToken, REFRESH_TOKEN_SECRET);

    // 从数据库查询用户
    const userInfo = await UserModel.findOne({ _id: decoded.id });

    if (!userInfo) {
      return res.send({
        code: 403,
        msg: "刷新 Token 无效",
      });
    }

    // 生成新的访问 Token
    const newAccessToken = jwt.sign({ id: userInfo._id }, ACCESS_TOKEN_SECRET, {
      expiresIn: "15m",
    });

    res.send({
      code: 200,
      msg: "刷新成功",
      accessToken: newAccessToken,
    });
  } catch (error) {
    res.send({
      code: 403,
      msg: "刷新 Token 无效或已过期",
    });
  }
});

// 手机号登录
router.post("/login/phone", async function (req, res) {
  const { phone, code } = req.body;

  // 参数验证
  if (!phone || !code) {
    return res.send({
      code: 400,
      msg: "手机号和验证码不能为空",
    });
  }

  // 验证手机号格式
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    return res.send({
      code: 400,
      msg: "手机号格式不正确",
    });
  }

  // 验证验证码
  const storedData = verificationCodes.get(phone);
  if (!storedData) {
    return res.send({
      code: 400,
      msg: "请先获取验证码",
    });
  }

  // 验证码5分钟内有效
  if (Date.now() - storedData.timestamp > 5 * 60 * 1000) {
    verificationCodes.delete(phone); // 删除过期的验证码
    return res.send({
      code: 400,
      msg: "验证码已过期，请重新获取",
    });
  }

  if (storedData.code !== code) {
    return res.send({
      code: 400,
      msg: "验证码错误",
    });
  }

  try {
    // 查找用户
    let userInfo = await UserModel.findOne({ phone });

    if (!userInfo) {
      return res.send({
        code: 404,
        msg: "该手机号未注册",
      });
    }

    // 生成访问 Token
    const accessToken = jwt.sign({ id: userInfo._id }, ACCESS_TOKEN_SECRET, {
      expiresIn: "15m",
    });

    // 生成刷新 Token
    const refreshToken = jwt.sign({ id: userInfo._id }, REFRESH_TOKEN_SECRET, {
      expiresIn: "7d",
    });

    // 验证成功后删除验证码
    verificationCodes.delete(phone);

    res.send({
      code: 200,
      msg: "登录成功",
      data: {
        id: userInfo._id,
        username: userInfo.userName,
        avatar: userInfo.img,
        sex: userInfo.sex,
        age: userInfo.age,
        phone: userInfo.phone,
        money: userInfo.money,
        vip: userInfo.vip,
      },
      accessToken,
      refreshToken,
    });
  } catch (error) {
    console.error("手机号登录错误:", error);
    res.send({
      code: 500,
      msg: "登录失败，请稍后重试",
    });
  }
});

module.exports = router;
